package com.plian.system.service.ms.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.wtzg.RectificationSituationExcelBean;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.entity.ms.RectificationSituation;
import com.plian.system.entity.sys.Message;
import com.plian.system.entity.sys.Org;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.excel.ImportResult;
import com.plian.system.mapper.ms.IssueSituationMapper;
import com.plian.system.mapper.ms.RectificationSituationMapper;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.ms.IRectificationSituationService;
import com.plian.system.service.ms.check.RectificationExcelCheckData;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.wfTwo.WorkflowTwoService;
import com.plian.system.vo.ms.RectificationSituationVO;
import com.plian.system.wrapper.ms.RectificationSituationWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 月度计划表 服务实现类
 *
 * @author xiaohu
 */
@Slf4j
@Service
@AllArgsConstructor
public class RectificationSituationServiceImpl extends BaseServiceImpl<RectificationSituationMapper, RectificationSituation> implements IRectificationSituationService, BaseFlowService {

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private RectificationSituationMapper rectificationSituationMapper;

    private OrgzationService orgzationService;

    private FileService fileService;

    private RectificationSituationWrapper rectificationSituationWrapper;

    private IOrgService orgService;

    private IssueSituationMapper issueSituationMapper;

    private IMessageService messageService;

    private UserDao userDao;

    private GzwProperties gzwProperties;
    private static Map<String, String> fileNameMap = new HashMap<>();
    @Autowired
    BaseInfoDao baseInfoDao;
    private Environment environment;
    // 字典map
    private static HashMap<String, List<String>> codeMap = new HashMap<>();
    //名称转cod 用参照字典（参照key,<name,id>）(需确保每个名字唯一)
    private static HashMap<String, Map<String, String>> nameMap = new HashMap<>();
    private BaseInfoService baseInfoService;
    private OrgzationDao orgzationDao;

    @Autowired
    private WorkflowTwoService workflowTwoService;
    /**
     * 转换格林威治时间
     *
     * @param dateTime
     * @return
     */
    private static String covnDate(String dateTime) {
        DateFormat df2 = null;
        Date date1 = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Date date = df.parse(dateTime);
            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            dateTime = dateTime.substring(0, 10);
            return dateTime;
        }
        return df2.format(date1);
    }

    @Override
    public HashMap<String, Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }

    @Override
    public Boolean finish(String id) {
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public Boolean checkIsExisted(Long id, String code) {
        if (Optional.ofNullable(code).isPresent()) {
            RectificationSituation rectificationSituation = new RectificationSituation();
            rectificationSituation.setCode(code);
            if (Optional.ofNullable(getOne(Condition.getQueryWrapper(rectificationSituation))).isPresent()) {
                if (id == null || !id.equals(getOne(Condition.getQueryWrapper(rectificationSituation)).getId())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean submit(RectificationSituation rectificationSituation) {
        if (!Optional.ofNullable(rectificationSituation.getStatus()).isPresent()) {
            rectificationSituation.setStatus(FormStatusConstant.UNREVIEWED);
        }
        boolean flag = false;
        if (rectificationSituation.getId() == null) {
            flag = true;
        }
        boolean result = saveOrUpdate(rectificationSituation);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(rectificationSituation.getId()), rectificationSituation.getFormType(), processVariable);
        if (flag) {
            fileService.saveAll(String.valueOf(rectificationSituation.getId()), rectificationSituation.getDocList());
        } else {
            fileService.edit(String.valueOf(rectificationSituation.getId()), rectificationSituation.getDocList());
        }
        if(result){
            if(rectificationSituation.getStatus()!=null&&rectificationSituation.getStatus()==3){//如果是审批之后再次修改之后就对数据进行反审核
//                workFlowFormTwoService.goBackToStash(Integer.valueOf(rectificationSituation.getFormType()), String.valueOf(rectificationSituation.getId()));
                goBackToStash(String.valueOf(rectificationSituation.getId()));
                workflowTwoService.goBackToStash(String.valueOf(rectificationSituation.getId()), Integer.valueOf(rectificationSituation.getFormType()));
            }
        }
        return result;
    }

    @Override
    public Boolean checkCancel(Long id) {
        RectificationSituation rectificationSituation = getById(id);
        if (!Optional.ofNullable(rectificationSituation).isPresent()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean saveOrUpdate(RectificationSituation rectificationSituation) {
        if (!Optional.ofNullable(rectificationSituation.getStatus()).isPresent()) {
            rectificationSituation.setStatus(UNREVIEWED);
        }
        boolean flag = false;
        if (!Optional.ofNullable(rectificationSituation.getId()).isPresent()) {
            //根据单据类型生成单据编码
            rectificationSituation.setCode(formCodeService.getCode(FormTypeConstant.MS_RECTIFICATION_SITUATION));
            rectificationSituation.setFormType(String.valueOf(FormTypeConstant.MS_RECTIFICATION_SITUATION));
            flag = true;
        }
        boolean result = super.saveOrUpdate(rectificationSituation);
        return result;
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id           主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            RectificationSituation rectificationSituation = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH) {
                rectificationSituation.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                rectificationSituation.setApprovedTime(now);
            }
            rectificationSituation.setStatus(updateStatus);
            updateById(rectificationSituation);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        QueryWrapper<RectificationSituation> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
        List<RectificationSituation> rectificationSituations = list(queryWrapper);
        List<RectificationSituationVO> rectificationSituationVOS = rectificationSituationWrapper.entityToVO(rectificationSituations);
        List<PageData> pageDataList = new ArrayList<>();
        try {
            if (CollectionUtil.isNotEmpty(rectificationSituationVOS)) {
                for (RectificationSituationVO vo : rectificationSituationVOS) {
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillCompanyName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getFillCompanyName());
                    pd.put("formType", FormTypeConstant.MS_RECTIFICATION_SITUATION);
                    pd.put("orgName", vo.getFillCompanyName());
                    pageDataList.add(pd);
                }
            }
            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.MS_RECTIFICATION_SITUATION);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    @Override
    public List<PageData> orgBydate(PageData pageData) {
        ArrayList<String> orgIds = (ArrayList<String>) pageData.get("orgIds");
        String endTime = pageData.getString("endTime");
        String startTime = endTime + "-01";
        endTime = endTime + "-31";
        ArrayList<PageData> pdlist = new ArrayList<>();
        for (String orgid : orgIds) {
            PageData pd1 = new PageData();
            pd1.put("orgId", orgid);
            pd1.put("startTime", startTime);
            pd1.put("endTime", endTime);
            List<PageData> list = rectificationSituationMapper.orgBydate(pd1);
            for (PageData pageData1 : list) {
                if (pageData1.getString("fillCompanyId") != null) {
                    PageData org = orgzationService.getCompanyNameById(pageData1.getString("fillCompanyId"));
                    if (org != null) {
                        pageData1.put("orgName", org.getString("name"));
                    }
                    String fillDate = pageData1.getString("fillDate");
                    fillDate = RectificationSituationServiceImpl.covnDate(fillDate);
                    pageData1.put("fillDate", fillDate);
                    pdlist.add(pageData1);
                }
            }
        }
        return pdlist;
    }

    @Override
    public List<PageData> orgBymonth(PageData pageData) {
        ArrayList<String> orgIds = (ArrayList<String>) pageData.get("orgIds");
        String endTime = pageData.getString("endTime");
        String startTime = pageData.getString("startTime");
        Date nowTime = DateUtil.now();
        String now = DateUtil.format(nowTime, "yyyy-MM");
        if (startTime == null) {
            startTime = now.split("-")[0] + "-01";
        }
        if (endTime == null) {
            endTime = now;
        }
        endTime = endTime + "-31";
        startTime = startTime + "-01";
        ArrayList<PageData> pdlist = new ArrayList<>();
        for (String orgid : orgIds) {
            PageData pd1 = new PageData();
            pd1.put("orgId", orgid);
            pd1.put("startTime", startTime);
            pd1.put("endTime", endTime);
            List<PageData> list = rectificationSituationMapper.orgBydate(pd1);
            for (PageData pageData1 : list) {
                if (pageData1.getString("fillCompanyId") != null) {
                    PageData org = orgzationService.getCompanyNameById(pageData1.getString("fillCompanyId"));
                    if (org != null) {
                        pageData1.put("orgName", org.getString("name"));
                    }
                    String fillDate = pageData1.getString("fillDate");
                    fillDate = RectificationSituationServiceImpl.covnDate(fillDate);
                    pageData1.put("fillDate", fillDate);
                    pdlist.add(pageData1);
                }
            }
        }
        return pdlist;
    }

    @Override
    public void sendMessage(RectificationSituation situation){
        List<Message> messages = new ArrayList<>();
        RectificationSituation rectificationSituation = getById(situation.getId());
        //获取13家
        List<Org> units = orgService.directlyUnderUnitNoChild(false).getList();
        List<String> orgIds = units.stream().map(Org::getId).collect(Collectors.toList());
        Org fillOrg = orgService.getById(rectificationSituation.getFillCompanyId());
        //获取人员
        PageData data = new PageData();
        data.put("orgIds", orgIds);
        data.put("funName", "问题整改");
        try {
            List<PageData> pageDatas = userDao.findCompanyUserByConfigFunAndOrgIds(data);
            String userId = TokenUtil.getTokenUserId();
            //下发企业的人
            if (CollectionUtil.isNotEmpty(pageDatas)) {
                for (PageData pageData : pageDatas) {
                    String orgId = pageData.getString("orgId");
                    String orgName = units.stream().filter(m -> orgId.equals(m.getId())).map(Org::getName).findFirst().get();

                    Message message = Message.builder().formId(rectificationSituation.getId() + "").orgName(orgName)
                            .orgId(orgId).formType(rectificationSituation.getFormType()).formTypeName("整改情况").messageTime(DateUtil.now())
                            .createUser(pageData.getString("userId")).message("典型案例推送")
                            .sendUser(userId).sendUserName(gzwProperties.getName()).isIgnore(0).build();

                    messages.add(message);
                }
            }
            messageService.saveBatch(messages);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    @Async("ttlExecutor")
    public Future<ImportResult> importExcel(String progressId, InputStream inputStream) {
        String progress = "progress";
        Date now = DateUtil.now();
        String key = progressId + "#half:hour";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //在所有校验前统一初始化所有字典
        initMap();

        try {
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream = new ByteArrayInputStream(bytes);
            List<Object> baseList = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(0).headRowNumber(3).head(RectificationSituationExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> baseList.addAll(list))).build());
            int size = baseList.size();
            ImportResult importResult = RectificationExcelCheckData.checkStaffData(baseList, key, codeMap, nameMap);
            if (!importResult.isSuccess()) {
                CacheUtil.put(progress, progress, key, importResult.getMsg());
                return new AsyncResult<>(importResult);
            }
            if(baseList!=null&&baseList.size()>0){
                int count = 0;

                for (Object obj: baseList) {
                    RectificationSituationExcelBean rectificationSituationExcelBean=(RectificationSituationExcelBean)obj;
                    RectificationSituation rectificationSituation=new RectificationSituation();
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getContentSketch())){//具体问题
                        rectificationSituation.setContentSketch(rectificationSituationExcelBean.getContentSketch());
                    }
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getProblemDescription())){//问题概述
                        rectificationSituation.setProblemDescription(rectificationSituationExcelBean.getProblemDescription());
                    }
//                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getViolateTerm())){//违反条例
//                        rectificationSituation.setViolateTerm(rectificationSituationExcelBean.getViolateTerm());
//                    }
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getChangeMeasures())){//整改措施
                        rectificationSituation.setChangeMeasures(rectificationSituationExcelBean.getChangeMeasures());
                    }
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getChangeProposal())){//整改建议
                        rectificationSituation.setChangeProposal(rectificationSituationExcelBean.getChangeProposal());
                    }
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getDeadlineDate())){//整改时限
                        rectificationSituation.setDeadlineDate(rectificationSituationExcelBean.getDeadlineDate());
                    }
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getObligationLeader())){//责任领导
                        rectificationSituation.setObligationLeader(rectificationSituationExcelBean.getObligationLeader());
                    }
                    PageData org = orgzationService.findByName(rectificationSituationExcelBean.getCompanyName(),TokenUtil.getCompetentOrganization());
                    if(org!=null&&org.getString("id")!=null){
                        rectificationSituation.setCompanyId(org.getString("id"));
                    }else{
                        return getAsyncResult(baseList,obj,"责任单位",rectificationSituationExcelBean.getCompanyName(),"未找到对象");
                    }

                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getIssueType())){
                        rectificationSituation.setIssueType(rectificationSituationExcelBean.getIssueType());
                    }
                    String situationeCode="";
                    if(StringUtil.isNotBlank(rectificationSituationExcelBean.getRectificationSituation())){
                        try{
                            List<PageData> pageDataList=baseInfoDao.findbyParentid("124");
                            if(pageDataList!=null&&pageDataList.size()>0){
                                for (PageData pageData: pageDataList) {
                                    String code=pageData.getString("code");
                                    String name=pageData.getString("name");
                                    if(StringUtil.isNotBlank(code)&&name.equals(rectificationSituationExcelBean.getRectificationSituation())){
                                        situationeCode=code;
                                    }
                                }
                            }
                        } catch (Exception e){
                            e.getStackTrace();
                            return getAsyncResult(baseList,obj,"完成情况",rectificationSituationExcelBean.getRectificationSituation(),"未找到对象");
                        }
                    }else{
                        return getAsyncResult(baseList,obj,"完成情况",rectificationSituationExcelBean.getRectificationSituation(),"未填写");
                    }

                    rectificationSituation.setRectificationSituation(situationeCode);
                    rectificationSituation.setFillCompanyId(TokenUtil.getTokenOrgId());
                    rectificationSituation.setFillDate(sdf.format(new Date()));
                    rectificationSituation.setCreateUser(TokenUtil.getTokenUserId());
                    rectificationSituation.setCreateTime(now);
                    rectificationSituation.setUpdateTime(now);
                    rectificationSituation.setCreateCompanyId(TokenUtil.getTokenOrgId());
                    saveOrUpdate(rectificationSituation);
                    count++;
                    int value = count * 100 / size;
                    CacheUtil.put(progress, progress, key, value + 100);
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("导入失败");
            CacheUtil.put(progress, progress, key,"导入失败");
            return new AsyncResult<>(new ImportResult(false,"导入失败"));
        }
        CacheUtil.put(progress, progress, key,"导入成功");
        return new AsyncResult<>(new ImportResult(true,"导入成功"));
    }
    public AsyncResult<ImportResult> getAsyncResult(List<Object> baseList,Object obj,String one,String objMsg,String two){
        StringBuilder msg = new StringBuilder();
        int index = baseList.indexOf(obj);
        msg.append(ImportExcelUtil.msgBuilder("2", String.valueOf(index + 2), one, objMsg, two));
        return new AsyncResult<>(new ImportResult(false, msg.toString()));
    }

/*    public IssueSituation searchIssueSituationCode(String code) {
        return issueSituationMapper.selectOne(new LambdaQueryWrapper<IssueSituation>().eq(IssueSituation::getCode, code)
                .eq(IssueSituation::getFillCompanyId, TokenUtil.getTokenOrgId()));
    }*/
/*    public IssueSituation searchIssueSituationId(Long id) {
        return issueSituationMapper.selectOne(new LambdaQueryWrapper<IssueSituation>().eq(IssueSituation::getId, id));
    }*/
    @Override
    public String export(){
        String key = System.currentTimeMillis() + StringPool.DASH + UUID.randomUUID().toString().replace(StringPool.DASH, "");
        String fileName = key + ".xlsx";
        String exportPath = environment.getProperty("excel.path");

        /**
         * 导出路径不存在则创建
         */
        File file = new File(exportPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/rectificationExport.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(exportPath + fileName).withTemplate(inputStream).build();

        // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
        // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
        // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存

        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        // 表二
        WriteSheet staffFilesWriteSheet = EasyExcel.writerSheet(0).build();
        LambdaQueryWrapper<RectificationSituation> queryWrapper= new LambdaQueryWrapper<RectificationSituation>();
        queryWrapper.eq(RectificationSituation::getCreateCompanyId, TokenUtil.getTokenOrgId());
        queryWrapper.orderByDesc(RectificationSituation::getCreateTime);

        List<RectificationSituation> rectificationSituationlist=super.list(queryWrapper);
        List<RectificationSituationVO> vos = rectificationSituationWrapper.entityToVO(rectificationSituationlist);
        List<RectificationSituationExcelBean> rectificationSituationExcelBeans=new ArrayList<>();
        Integer serialNumber=0;
        if(CollectionUtil.isNotEmpty(vos)){
            for (RectificationSituationVO rectificationSituation: vos) {
                if(rectificationSituation!=null){
                    serialNumber=serialNumber+1;
                    RectificationSituationExcelBean rectificationSituationExcelBean=new RectificationSituationExcelBean();
                    rectificationSituationExcelBean.setSerialNumber(String.valueOf(serialNumber));
                    if(StringUtil.isNotBlank(rectificationSituation.getProblemDescription())){
                        rectificationSituationExcelBean.setProblemDescription(rectificationSituation.getProblemDescription());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getContentSketch())){
                        rectificationSituationExcelBean.setContentSketch(rectificationSituation.getContentSketch());
                    }
//                    if(StringUtil.isNotBlank(rectificationSituation.getViolateTerm())){
//                        rectificationSituationExcelBean.setViolateTerm(rectificationSituation.getViolateTerm());
//                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getChangeProposal())){
                        rectificationSituationExcelBean.setChangeProposal(rectificationSituation.getChangeProposal());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getChangeMeasures())){
                        rectificationSituationExcelBean.setChangeMeasures(rectificationSituation.getChangeMeasures());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getDeadlineDate())){
                        rectificationSituationExcelBean.setDeadlineDate(rectificationSituation.getDeadlineDate());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getObligationLeader())){
                        rectificationSituationExcelBean.setObligationLeader(rectificationSituation.getObligationLeader());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getCompanyId())){
                        PageData orgIdPageDate=new PageData();
                        orgIdPageDate.put("id",rectificationSituation.getCompanyId());
                        ObjResult org = orgzationService.findbyid(orgIdPageDate);
                        if(org!=null&&org.getPageData()!=null){
                            if(StringUtil.isNotBlank(org.getPageData().getString("orgName"))){
                                rectificationSituationExcelBean.setCompanyName(org.getPageData().getString("orgName"));
                            }
                        }
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getIssueType())){
                        rectificationSituationExcelBean.setIssueType(rectificationSituation.getIssueType());
                    }
                    if(StringUtil.isNotBlank(rectificationSituation.getRectificationSituation())){
                        try {
                            PageData p = baseInfoDao.findbycode(rectificationSituation.getRectificationSituation());
                            if(p!=null){
                                String name=p.getString("name");
                                if(StringUtil.isNotBlank(name)){
                                    rectificationSituationExcelBean.setRectificationSituation(name);
                                }
                            }
                        }catch (Exception e){
                            e.getStackTrace();
                        }
                    }
                    rectificationSituationExcelBean.setFillDate(rectificationSituation.getFillDate());
                    rectificationSituationExcelBean.setFillCompanyName(rectificationSituation.getFillCompanyName());
                    rectificationSituationExcelBeans.add(rectificationSituationExcelBean);

                }
            }
        }
        excelWriter.fill(rectificationSituationExcelBeans, fillConfig, staffFilesWriteSheet);
        excelWriter.finish();
        PageData org = orgzationService.getCompanyNameById(TokenUtil.getTokenOrgId());
        String companyName = "";
        if (org != null) {
            companyName = org.getString("name");
        }
        String excelName = companyName + "_问题整改";
        fileNameMap.put(key, excelName);
        return key;
    }
    @Override
    public void download(String key, HttpServletResponse response) {
        if (!fileNameMap.containsKey(key)) {
            log.error("BaseInvestmentPlanServiceImpl 导出excel失败--------> key " + key);
            return;
        }
        String excelName = fileNameMap.get(key);
        String excelPath = environment.getProperty("excel.path") + "/" + key + ".xlsx";
        FileTools.exportExcel(excelPath, excelName, response);
        fileNameMap.remove(key);
    }

    private void initMap() {
        //注：以下key值与实际配置的参照无关联，仅为了方便理解使用了相同名称
        //完成情况


        try {
            List<PageData> pageDataList=baseInfoDao.findbyParentid("124");
            List<String> a=new ArrayList<>();
            for (PageData pageData: pageDataList) {
                String name=pageData.getString("name");
                a.add(name);
            }
            codeMap.put("RectificationSituationRef", a);
            List<PageData> allOrgs = orgzationDao.list(null);
            //单位
            if (CollectionUtil.isNotEmpty(allOrgs)) {
                HashMap<String, String> orgMap = new HashMap<>();
                for (PageData pageData : allOrgs) {
                    orgMap.put((String) pageData.get("name"), (String) pageData.get("id"));
                }
                nameMap.put("unitRef", orgMap);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }
}
